package com.henghai.zhenxuan;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.Nullable;

import com.henghai.zhenxuan.data.config.AppConfig;
import com.henghai.zhenxuan.data.config.Const;
import com.henghai.zhenxuan.domain.event.Messages;
import com.henghai.zhenxuan.domain.message.PageMessenger;
import com.henghai.zhenxuan.listener.InstallReceiver;
import com.henghai.zhenxuan.utils.HiStatusBar;
import com.henghai.zhenxuan.utils.MainHandler;
import com.henghai.zhenxuan.utils.Utils;
import com.kongzue.dialogx.dialogs.TipDialog;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.kunminx.architecture.ui.page.BaseActivity;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.page.StateHolder;
import com.kunminx.architecture.utils.ToastUtils;
import com.windmill.sdk.WMConstants;
import com.windmill.sdk.WindMillError;
import com.windmill.sdk.interstitial.WMInterstitialAd;
import com.windmill.sdk.interstitial.WMInterstitialAdListener;
import com.windmill.sdk.interstitial.WMInterstitialAdRequest;
import com.windmill.sdk.models.AdInfo;
import com.windmill.sdk.reward.WMRewardAd;
import com.windmill.sdk.reward.WMRewardAdListener;
import com.windmill.sdk.reward.WMRewardAdRequest;
import com.windmill.sdk.reward.WMRewardInfo;

import java.util.HashMap;
import java.util.Map;


public class MainActivity extends BaseActivity {
    // 激励视频广告
    private WMRewardAd mRewardVideoAd;
    // 插屏广告
    private WMInterstitialAd mInterstitialAd;
    //    private ATRewardVideoAd mRewardVideoAd;
//    private ATInterstitial mInterstitialAd;
    private String userId = "";
    private InstallReceiver receiver;
    private long mLastClickBackTime;//上次点击back键的时间

    public static void launch(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    private String TAG = "MainActivity-激励";
    private String TAG1 = "MainActivity-插屏";
    private MainActivityStates mStates;


    private PageMessenger mMessenger;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(MainActivityStates.class);
        mMessenger = getApplicationScopeViewModel(PageMessenger.class);
    }

    //显示插屏广告
    public void showInnerAd() {
        if (!Const.ISSHOWAD) {//是否显示插屏广告
            return;
        }
        if (mInterstitialAd != null && mInterstitialAd.isReady()) {
            HashMap option = new HashMap();
            option.put(WMConstants.AD_SCENE_ID, userId);
            option.put(WMConstants.AD_SCENE_DESC, "页面切换");
            mInterstitialAd.show(MainActivity.this, option);
        } else {
            initIntersAd();
        }
    }

    //显示激励广告
    private void showRewardAd() {
        if (mRewardVideoAd != null && mRewardVideoAd.isReady()) {
            HashMap option = new HashMap();
            option.put(WMConstants.AD_SCENE_ID, userId);
            option.put(WMConstants.AD_SCENE_DESC, "获取饲料");
            mRewardVideoAd.show(MainActivity.this, option);
        } else {
            initRewardVideoAd();
        }
    }

    //初始化激励广告
    private void initRewardVideoAd() {
//        String rewardKey = AppConfig.INSTANCE.getMConfigs().login().get().getPlacementIdThree();
        String rewardKey = AppConfig.INSTANCE.getMConfigs().login().get().getTobidReward();
//        rewardKey = "1391362621388445";
        Log.d(TAG, "initRewardVideoAd: "+ rewardKey);
        if (rewardKey == null || rewardKey.isEmpty()) {
            return;
        }

        Map<String, Object> options = new HashMap<>();
        options.put("user_id", String.valueOf(userId));

        mRewardVideoAd = new WMRewardAd(this, new WMRewardAdRequest(rewardKey, userId, options));
//        mRewardVideoAd = new WMRewardAd(this, AppConfig.INSTANCE.getMConfigs().login().get().getPlacementIdThree());
//        mRewardVideoAd.setAdListener(new RewardViewListener() {
//            @Override
//            public void onRewardedVideoAdPlayStart(ATAdInfo atAdInfo) {
//                mRewardVideoAd.load();
//            }
//
//            @Override
//            public void onReward(ATAdInfo atAdInfo) {
//                TipDialog.show("恭喜获得奖励", WaitDialog.TYPE.SUCCESS);
//                mMessenger.input(new Messages(Messages.EVENT_SHOW_REWARD_AD_SUCCESS));
//            }
//        });
        mRewardVideoAd.setRewardedAdListener(new WMRewardAdListener() {
            @Override
            public void onVideoAdLoadSuccess(String placementId) {
                Log.d(TAG, "onVideoAdLoadSuccess: " + placementId);
            }

            @Override
            public void onVideoAdLoadError(WindMillError error, String placementId) {
                Log.d(TAG, "onVideoAdLoadError: "+ error.toString() + " placementId:"+ placementId);
            }

            @Override
            public void onVideoAdPlayStart(AdInfo adInfo) {
                mRewardVideoAd.loadAd();
            }

            @Override
            public void onVideoAdPlayError(WindMillError error, String placementId) {
                Log.d(TAG, "onVideoAdPlayError: "+ error.toString() + " placementId:"+ placementId);
            }

            @Override
            public void onVideoAdPlayEnd(AdInfo adInfo) {
                Log.d(TAG, "onVideoAdPlayEnd: " + adInfo.toString());
            }

            @Override
            public void onVideoAdClicked(AdInfo adInfo) {
                Log.d(TAG, "onVideoAdClicked: " + adInfo.toString());
            }

            @Override
            public void onVideoAdClosed(AdInfo adInfo) {
                Log.d(TAG, "onVideoAdClosed: " + adInfo.toString());
            }

            @Override
            public void onVideoRewarded(AdInfo adInfo, WMRewardInfo rewardInfo) {
                TipDialog.show("恭喜获得奖励", WaitDialog.TYPE.SUCCESS);
                mMessenger.input(new Messages(Messages.EVENT_SHOW_REWARD_AD_SUCCESS));
            }
        });
        mRewardVideoAd.loadAd();
    }

    //初始化插屏广告
    public void initIntersAd() {
//        String mIntersKey = AppConfig.INSTANCE.getMConfigs().login().get().getPlacementIdTwo();
        String mIntersKey = AppConfig.INSTANCE.getMConfigs().login().get().getTobibInner();
        Log.d(TAG, "initIntersAd: "+ mIntersKey);
//        mIntersKey = "5137679357169019";
        if (mIntersKey == null || mIntersKey.isEmpty()) {
            return;
        }
        if (mInterstitialAd == null) {
            Map<String, Object> options = new HashMap<>();
            options.put("user_id", String.valueOf(userId));
            mInterstitialAd = new WMInterstitialAd(this, new WMInterstitialAdRequest(mIntersKey, userId, options));
//            mInterstitialAd = new ATInterstitial(this, mIntersKey);
            mInterstitialAd.setInterstitialAdListener(new WMInterstitialAdListener() {
                @Override
                public void onInterstitialAdLoadSuccess(String placementId) {
                    Log.d(TAG1, "onInterstitialAdLoadSuccess: " + placementId);
                    showInnerAd();
                }

                @Override
                public void onInterstitialAdPlayStart(AdInfo adInfo) {
                    Log.d(TAG1, "onInterstitialAdPlayStart: " + adInfo.toString());
                }

                @Override
                public void onInterstitialAdPlayEnd(AdInfo adInfo) {
                    Log.d(TAG1, "onInterstitialAdPlayEnd: " + adInfo.toString());
                    AppConfig.INSTANCE.setInnerAdCount(AppConfig.INSTANCE.getInnerAdCount() + 1);
                }

                @Override
                public void onInterstitialAdClicked(AdInfo adInfo) {
                    Log.d(TAG1, "onInterstitialAdClicked: " + adInfo.toString());
                }

                @Override
                public void onInterstitialAdClosed(AdInfo adInfo) {
                    Log.d(TAG1, "onInterstitialAdClosed: " + adInfo.toString());
                }

                @Override
                public void onInterstitialAdLoadError(WindMillError error, String placementId) {
                    Log.d(TAG1, "onInterstitialAdLoadError: " + error.toString() + " " + placementId);
                }

                @Override
                public void onInterstitialAdPlayError(WindMillError error, String placementId) {
                    Log.d(TAG1, "onInterstitialdPlayError: a" + error.toString() + " " + placementId);
                }
            });
            mInterstitialAd.loadAd();
//            mInterstitialAd.setAdListener(new InterstitialAdListener() {
//                @Override
//                public void onInterstitialAdVideoStart(ATAdInfo atAdInfo) {
//                    super.onInterstitialAdVideoStart(atAdInfo);
//                    Log.d(TAG, "onInterstitialAdVideoStart: " + atAdInfo.toString());
//                }
//                @Override
//                public void onInterstitialAdShow(ATAdInfo atAdInfo) {
//                    AppConfig.INSTANCE.setInnerAdCount(AppConfig.INSTANCE.getInnerAdCount() + 1);
//                    Log.d(TAG, "onInterstitialAdShow: " + atAdInfo.toString());
//                }
//                @Override
//                public void onInterstitialAdLoaded() {
//                    super.onInterstitialAdLoaded();
//                    showInnerAd();
//                    Log.d(TAG, "onInterstitialAdLoaded: 广告加载成功");
//                }
//                @Override
//                public void onInterstitialAdLoadFail(AdError adError) {
//                    super.onInterstitialAdLoadFail(adError);
//                    Log.d(TAG, "onInterstitialAdLoadFail: " + adError.toString());
//                }
//                @Override
//                public void onInterstitialAdVideoEnd(ATAdInfo atAdInfo) {
//                    super.onInterstitialAdVideoEnd(atAdInfo);
//                    Log.d(TAG, "onInterstitialAdVideoEnd: " + atAdInfo.toString());
//                }
//                @Override
//                public void onInterstitialAdVideoError(AdError adError) {
//                    super.onInterstitialAdVideoError(adError);
//                    Log.d(TAG, "onInterstitialAdVideoError: " + adError.toString());
//                }
//                @Override
//                public void onInterstitialAdClose(ATAdInfo atAdInfo) {
//                    super.onInterstitialAdClose(atAdInfo);
//                    Log.d(TAG, "onInterstitialAdClose: " + atAdInfo.toString());
//                }
//                @Override
//                public void onInterstitialAdClicked(ATAdInfo atAdInfo) {
//                    super.onInterstitialAdClicked(atAdInfo);
//                    Log.d(TAG, "onInterstitialAdClicked: " + atAdInfo.toString());
//                }
//            });
        }
//        Map<String, Object> localMap = new HashMap<>();
//        mInterstitialAd.setLocalExtra(localMap);

    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        HiStatusBar.INSTANCE.setStatusBar(this, false, Color.TRANSPARENT, true);
        userId = AppConfig.INSTANCE.getMConfigs().user().get().getUserId() + "";
        if (Const.ISSHOWAD){
            MainHandler.INSTANCE.postDelay(2500, this::initIntersAd);
            initRewardVideoAd();
        }
        mMessenger.output(this, messages -> {
            if (messages.eventId == Messages.EVENT_SHOW_INNER_AD) {
                showInnerAd();
            } else if (messages.eventId == Messages.EVENT_SHOW_REWARD_AD) {
                showRewardAd();
            }
        });

        // 在Activity或其他组件中注册BroadcastReceiver
        IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
        filter.addDataScheme("package"); // 这行代码很重要，它限制了Intent只对"package"数据模式的广播作出反应
        receiver = new InstallReceiver();
        registerReceiver(receiver, filter);

        Utils.checkUpdate(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_main, BR.vm, mStates);
    }

    public static class MainActivityStates extends StateHolder {

    }


}
